//
//  GolfViewController.m
//  Golf
//
//  Created by mrbradle on 11/28/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GolfViewController.h"


@implementation GolfViewController

@synthesize currentPlayer;
@synthesize playerVCs2;
@synthesize game,playerVCs,cardImages;
@synthesize roundLabel,nameLabel,scoreLabel,drawButton,discardButton,passButton,drawnCard;
@synthesize cardButton1,cardButton2,cardButton3,cardButton4;
@synthesize knockButton,nextButton;

+ (int)CENTER_X { return 160; }
+ (int)CENTER_Y { return 175; }
+ (int)RADIUS_X { return 114; }
+ (int)RADIUS_Y { return 130; }


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)initGame:(GolfGame*)game_ {
    self.game = game_;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)updateView {
    
    //GolfPlayer* temp = [self.game.players objectAtIndex:self.game.turn]; //The player whose turn it is
    GolfPlayer* temp = [self.game.players objectAtIndex:self.currentPlayer]; //The player whose turn it is
    
    nameLabel.text = temp.name;
    scoreLabel.text = [NSString stringWithFormat:@"Score: %d",temp.score];
    roundLabel.text = [NSString stringWithFormat:@"Round: %d/%d",game.round,game.numRounds];
    
    [cardButton1 setBackgroundImage:self.cardImages[temp.cards[0]] forState:UIControlStateNormal];
    [cardButton2 setBackgroundImage:self.cardImages[temp.cards[1]] forState:UIControlStateNormal];
    [cardButton3 setBackgroundImage:self.cardImages[temp.cards[2]] forState:UIControlStateNormal];
    [cardButton4 setBackgroundImage:self.cardImages[temp.cards[3]] forState:UIControlStateNormal];
    
    for (int i = 1; i < game.numPlayers; i++) {
        //Update the names of all the other players
        //PlayerViewController* temp2 = [self.playerVCs objectAtIndex:i];
        PlayerViewController* temp2 = self.playerVCs2[i];
        GolfPlayer* temp3 = [self.game.players objectAtIndex:(self.currentPlayer+i) % self.game.numPlayers];
        //NSLog(@"%@%@",temp2.nameLabel.text,temp3.name);
        [temp2.nameLabel setText:[NSString stringWithString:temp3.name]];
        NSLog(@"%d %d %d",i,currentPlayer+i,game.knocker);
        if (!game.roundOver && game.knocker == (self.currentPlayer+i) % self.game.numPlayers) {
            [temp2.actionLabel setText:@"(KNOCKED)"];
        } else {
            [temp2.actionLabel setText:@""];
        }
        //[temp2 updateName:temp3.name];
        //NSLog(@"%@",temp2.nameLabel.text);
        //temp2.nameLabel.text = temp3.name;
    }
    
    if (!game.roundOver) { //standard play mode.  all cards and buttons should function normally at this point
    
        drawButton.hidden = discardButton.hidden = drawnCard.hidden = NO;
        cardButton1.enabled = cardButton2.enabled = cardButton3.enabled = cardButton4.enabled = YES;
        
        nextButton.hidden = YES;
        knockButton.hidden = NO; //show knock button and not next button
        
        if (temp.faceDown[0]) [cardButton1 setBackgroundImage:self.cardImages[53] forState:UIControlStateNormal]; //hardcoding 4 again orz
        if (temp.faceDown[1]) [cardButton2 setBackgroundImage:self.cardImages[53] forState:UIControlStateNormal];
        if (temp.faceDown[2]) [cardButton3 setBackgroundImage:self.cardImages[53] forState:UIControlStateNormal];
        if (temp.faceDown[3]) [cardButton4 setBackgroundImage:self.cardImages[53] forState:UIControlStateNormal];
    
        [drawButton setBackgroundImage:self.cardImages[53] forState:UIControlStateNormal];
        [drawButton setBackgroundImage:self.cardImages[53] forState:UIControlStateDisabled];
        [discardButton setBackgroundImage:self.cardImages[self.game.topCard] forState:UIControlStateNormal];
        [discardButton setBackgroundImage:self.cardImages[self.game.topCard] forState:UIControlStateDisabled];

        //if (game.deckEmpty) {
            drawButton.hidden = game.deckEmpty; //don't let the player draw a card if there's none left
            passButton.hidden = !(game.deckEmpty && game.drawnCard == -1); //let the player pass if they want
        //}
        
        if (game.drawnCard != -1)
            [drawnCard setImage:self.cardImages[self.game.drawnCard]];
        
        drawButton.enabled = (game.drawnCard == -1);
        knockButton.enabled = (game.drawnCard == -1) && (game.knocker == -1);
        discardButton.enabled = (game.drawnCard != -1);
        drawnCard.hidden = (game.drawnCard == -1);
    
        /*for (int i = 1; i < game.numPlayers; i++) {
            //Update the names of all the other players
            //PlayerViewController* temp2 = [self.playerVCs objectAtIndex:i];
            PlayerViewController* temp2 = self.playerVCs2[i];
            GolfPlayer* temp3 = [self.game.players objectAtIndex:(self.currentPlayer+i) % self.game.numPlayers];
            //NSLog(@"%@%@",temp2.nameLabel.text,temp3.name);
            [temp2.nameLabel setText:[NSString stringWithString:temp3.name]];
            NSLog(@"%d %d %d",i,currentPlayer+i,game.knocker);
            if (game.knocker == (self.currentPlayer+i) % self.game.numPlayers) {
                [temp2.actionLabel setText:@"(KNOCKED)"];
            } else {
                [temp2.actionLabel setText:@""];
            }
            //[temp2 updateName:temp3.name];
            //NSLog(@"%@",temp2.nameLabel.text);
            //temp2.nameLabel.text = temp3.name;
        }*/
        
    } else { //endgame mode.  display all 4 cards and change the knock button to the next button
        
        drawButton.hidden = discardButton.hidden = drawnCard.hidden = passButton.hidden = YES;
        cardButton1.enabled = cardButton2.enabled = cardButton3.enabled = cardButton4.enabled = NO;
        
        nextButton.hidden = NO;
        knockButton.hidden = YES; //show next button
        
    }
    
    
    
}

- (IBAction)hya:(id)sender {
    //Either the round is over or the whole game is over.  only do this if the round is over
    
    if (!game.gameOver) {
        self.currentPlayer++;
        if (self.currentPlayer == game.numPlayers) return;
        //self.currentPlayer = self.currentPlayer % game.numPlayers;
        [self updateView];
        //NSLog(@"%d",self.currentPlayer);
    } else {
        //Game over.  go back to the previous screen
        //[self.view]
        //[self.view.navigationController popViewControllerAnimated:YES];
        
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
}

- (IBAction)swap:(id)sender {
    
    if (sender == cardButton1) 
        [game swap:0];
    else if (sender == cardButton2) 
        [game swap:1];
    else if (sender == cardButton3) 
        [game swap:2];
    else if (sender == cardButton4) 
        [game swap:3];
    
    //[self updateView];
    
    [self endTurn];
    
}

- (IBAction)draw {
    
    if (game.drawnCard == -1) {
        [game draw];
        [self updateView];
    }
    
}

- (IBAction)discard {
    
    if (game.drawnCard != -1) {
        [game discard];
        //[self updateView];
        
        [self endTurn];
    }
    
}

- (IBAction)knock {
    
    if (game.knocker == -1) {
        [game knock];
        self.currentPlayer = game.turn;
        [self updateView];
        
    }
    
}

- (IBAction)pass {
    
    [game endTurn];
    //[self updateView];
    
    [self endTurn];
    
}

//This method checks if the round is over or not
- (void)endTurn {
    
    self.currentPlayer = game.turn;
    [self updateView];
    
    //End round if the current player knocked last turn
    if (game.knocker == game.turn)
        [self endRound];
    
}

- (void)startRound {
    //Actually start the round
    
    [game startRound];
    
    //Set it such that it displays the starting player's hand
    
    self.currentPlayer = game.turn;
    
    //Now that we have our cards and other info, update our view
    
    [self updateView];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self hya:alertView];
}

- (void)endRound {
    //End game round
    [game endRound];
    
    //NSLog(@"HYA %@",self.playerVCs2[7]); DON'T UNCOMMENT THIS :P
    
    self.currentPlayer = 0;
    [self updateView];
    
    //Display an alert showing the hands and total score of each player.
    for (int i = game.numPlayers-1; i >= 0; i--) {
        GolfPlayer* player = (GolfPlayer*)[game.players objectAtIndex:i];
        UIAlertView* results = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Round %d end\n%@ Results", game.round, player.name]
                                                          message:[NSString stringWithFormat:@"Hand: %@ %@ %@ %@\nScore: %d\nTotal Score: %d",[NSString stringWithString:[game getStringFromCard:player.cards[0]]], [NSString stringWithString:[game getStringFromCard:player.cards[1]]], [NSString stringWithString:[game getStringFromCard:player.cards[2]]], [NSString stringWithString:[game getStringFromCard:player.cards[3]]], player.roundScore, player.score]
                                                         delegate:self
                                                cancelButtonTitle:@"Next"
                                                otherButtonTitles:nil, nil];
        
        [results show];
    }
    
    
    /*if (game.round >= game.numRounds) [self endGame];
    else {
        //Start a new round
        [self startRound];
    }*/
}

- (void)endGame {
    
    [game endGame];
    
    NSString* finalResults = @"";
    for (int i = 0; i < game.numPlayers; i++) {
        GolfPlayer* player = (GolfPlayer*)[game.players objectAtIndex:i];
        finalResults = [finalResults stringByAppendingString:[NSString stringWithFormat:@"%d: %@ (%d points)\n",i+1,player.name,player.score]];
    }
    UIAlertView* results = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Final Results"]
                                                      message:finalResults
                                                     delegate:self
                                            cancelButtonTitle:@"Next"
                                            otherButtonTitles:nil, nil];
    [results show];
    
}

- (IBAction)next {
    
    if (game.round >= game.numRounds) [self endGame];
    else {
        //Start a new round
        [self startRound];
    }
}
    
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    playerVCs2 = (PlayerViewController**)malloc(sizeof(PlayerViewController*)*game.numPlayers);
    //[playerVCs2 retain];
    
    // Load the images
    self.cardImages = (UIImage**)malloc(sizeof(UIImage*)*54);
    for (int i = 0; i < 52; i++)
        self.cardImages[i] = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i+1]];
    self.cardImages[52] = [UIImage imageNamed:@"b1fv"];
    self.cardImages[53] = [UIImage imageNamed:@"b2fv"];
    
    for (int i = 0; i < 54; i++)
        [self.cardImages[i] retain]; //if I don't do this, when you exit out and reenter the app it blows up rofl
    
    // Create the view controllers of each extra player
    for (int i = 1; i < game.numPlayers; i++) {
        GolfPlayer* temp = [game.players objectAtIndex:i];
        
        //Calculate the center position of each player view controller.  They should be placed in a circle
        
        PlayerViewController* temp2 = [[PlayerViewController alloc] initWithPlayer: temp
                                        x:[GolfViewController CENTER_X] +
                                          [GolfViewController RADIUS_X]*sin(2*M_PI*i/game.numPlayers) -
                                          [PlayerViewController WIDTH]/2
                                        y:[GolfViewController CENTER_Y] +
                                          [GolfViewController RADIUS_Y]*cos(2*M_PI*i/game.numPlayers) -
                                          [PlayerViewController HEIGHT]/2
                                       ];
        [playerVCs addObject:temp2];
        self.playerVCs2[i] = temp2;
        //[temp2 retain];
        [self.view addSubview:temp2.view];
        
    }
    
    [self updateView];
    
    //Start the first round of the game
    
    [self startRound];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
